package com.example.idachuappone.person.youhui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.example.idachuappone.BaseActivity;
import com.example.idachuappone.R;
import com.example.idachuappone.index.adapter.AdapterYouHui;
import com.example.idachuappone.person.entity.QuanResults;
import com.example.idachuappone.ui.OnRefreshListener;
import com.example.idachuappone.ui.RefreshListView;
import com.example.idachuappone.utils.CheckUtil;
import com.example.idachuappone.utils.ComUtil;
import com.example.idachuappone.utils.Constant;
import com.example.idachuappone.utils.MainToast;
import com.example.idachuappone.utils.NetUtil;
import com.example.idachuappone.utils.PrefUtil;
import com.lidroid.xutils.bitmap.BitmapGlobalConfig.BitmapCacheManagementTask;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

public class MyYouHuiActivity extends BaseActivity implements OnClickListener {
	private AdapterYouHui adapterYouHui;
	private Button btn_back;
	private Button btn_index;
	private Dialog dialogAddQuan;
	private Dialog dialogLoading;
	private EditText et_quan_ma;
	private List<QuanResults> list;
	private LinearLayout ll_no_data;
	private LinearLayout ll_no_network;
	private int page;
	private RefreshListView plv_youhui;

	public MyYouHuiActivity() {
		this.page = 1;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_you_hui);
		this.dialogLoading = ComUtil.createCusProgressSmallBlackBgDialog(this);
		initView();
		checkNet();
	}

	private void checkNet() {
		if (CheckUtil.checkNet(this)) {
			this.dialogLoading.show();
			initData();
			return;
		}
		this.ll_no_network.setVisibility(0);
	}

	private void initData() {
		NetUtil.get(this, getUrl(), 100, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				MyYouHuiActivity.this.ll_no_network
						.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
				MyYouHuiActivity.this.dialogLoading.dismiss();
				String json = NetUtil.unescapeUnicode(responseInfo.result);
				try {
					MyYouHuiActivity.this.list = new ArrayList();
					JSONObject jsonObject = new JSONObject(json);
					if (jsonObject.getInt("code") == 10000) {
						JSONArray jsonArray = new JSONObject(json).getJSONObject("data").getJSONArray("results");
						for (int i = 0; i < jsonArray.length(); i++) {
							QuanResults quanResults = new QuanResults();
							quanResults.parseJson(jsonArray.getJSONObject(i));
							MyYouHuiActivity.this.list.add(quanResults);
							if (i == 0) {
								PrefUtil.getInstance(MyYouHuiActivity.this).setYouhuiPersonDianId(quanResults.getId());
							}
						}
						MyYouHuiActivity.this.initAdapter();
						return;
					}
					MainToast.show(MyYouHuiActivity.this, jsonObject.getString("error"), 0);
				} catch (Exception e) {
					e.printStackTrace();
					MainToast.show(MyYouHuiActivity.this, "\u7cfb\u7edf\u7e41\u5fd9", 0);
				}
			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				MyYouHuiActivity.this.dialogLoading.dismiss();
				MyYouHuiActivity.this.ll_no_network.setVisibility(0);
			}
		});
	}

	private void initAdapter() {
		if (this.list == null || this.list.size() <= 0) {
			this.ll_no_data.setVisibility(0);
			return;
		}
		this.ll_no_data.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
		this.adapterYouHui.setList(this.list);
		this.adapterYouHui.notifyDataSetChanged();
	}

	private String getUrl() {
		return "http://www.idachu.cn/api/coupon/my/all?page=" + this.page;
	}

	private void initView() {
		this.ll_no_network = (LinearLayout) findViewById(R.id.ll_no_network);
		this.ll_no_network.setOnClickListener(this);
		this.btn_back = (Button) findViewById(R.id.btn_back);
		this.btn_back.setOnClickListener(this);
		this.btn_index = (Button) findViewById(R.id.btn_index);
		this.btn_index.setOnClickListener(this);
		this.plv_youhui = (RefreshListView) findViewById(R.id.plv_youhui);
		this.plv_youhui.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onLoadMoring() {
				MyYouHuiActivity myYouHuiActivity = MyYouHuiActivity.this;
				myYouHuiActivity.page = myYouHuiActivity.page + 1;
				MyYouHuiActivity.this.addData(MyYouHuiActivity.this.getUrl());
			}
		});
		this.adapterYouHui = new AdapterYouHui(this);
		this.plv_youhui.setAdapter(this.adapterYouHui);
		this.ll_no_data = (LinearLayout) findViewById(R.id.ll_no_data);
	}

	private void addData(String path) {
		NetUtil.get(this, path, 100, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String json = NetUtil.unescapeUnicode(responseInfo.result);
				try {
					JSONObject jsonObject = new JSONObject(json);
					if (jsonObject.getInt("code") == 10000) {
						JSONArray jsonArray = new JSONObject(json).getJSONObject("data").getJSONArray("results");
						List<QuanResults> listtmep = new ArrayList();
						for (int i = 0; i < jsonArray.length(); i++) {
							QuanResults quanResults = new QuanResults();
							quanResults.parseJson(jsonArray.getJSONObject(i));
							listtmep.add(quanResults);
						}
						if (listtmep == null || listtmep.size() <= 0) {
							MyYouHuiActivity.this.plv_youhui.hideFooterView(false);
							MyYouHuiActivity myYouHuiActivity = MyYouHuiActivity.this;
							myYouHuiActivity.page = myYouHuiActivity.page - 1;
							MainToast.show(MyYouHuiActivity.this, "\u6682\u65e0\u6570\u636e", 0);
							return;
						}
						MyYouHuiActivity.this.list.addAll(listtmep);
						MyYouHuiActivity.this.initAdapter();
						MyYouHuiActivity.this.plv_youhui.hideFooterView(true);
						return;
					}
					MainToast.show(MyYouHuiActivity.this, jsonObject.getString("error"), 0);
				} catch (Exception e) {
					e.printStackTrace();
					MainToast.show(MyYouHuiActivity.this, "\u7cfb\u7edf\u7e41\u5fd9", 0);
				}
			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				MyYouHuiActivity.this.plv_youhui.hideFooterView(true);
				MyYouHuiActivity myYouHuiActivity = MyYouHuiActivity.this;
				myYouHuiActivity.page = myYouHuiActivity.page - 1;
				MainToast.show(MyYouHuiActivity.this, MyYouHuiActivity.this.getResources().getString(R.string.netFail),
						0);
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back /* 2131165198 */:
			finish();
		case R.id.btn_index /* 2131165213 */:
			this.dialogAddQuan = getAddQuanDialog();
			this.dialogAddQuan.setCanceledOnTouchOutside(false);
			this.dialogAddQuan.show();
		case R.id.ll_no_network /* 2131165232 */:
			checkNet();
		default:
		}
	}

	private Dialog getAddQuanDialog() {
		View view = LinearLayout.inflate(this, R.layout.activity_add_you_hui, null);
		this.et_quan_ma = (EditText) view.findViewById(R.id.et_quan_ma);
		this.et_quan_ma.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (count == 1) {
					if ((s.length() + 1) % 5 == 0) {
						MyYouHuiActivity.this.et_quan_ma.setText(s + " ");
						if (s.length() < 18) {
							MyYouHuiActivity.this.et_quan_ma.setSelection(s.length() + 1);
						} else {
							MyYouHuiActivity.this.et_quan_ma.setSelection(s.length());
						}
					}
				} else if (count == 0 && s.length() > 0 && s.length() % 5 == 0) {
					MyYouHuiActivity.this.et_quan_ma.setText(s.subSequence(0, s.length() - 1));
					MyYouHuiActivity.this.et_quan_ma.setSelection(s.length() - 1);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		Builder builder = new Builder(this);
		builder.setView(view);
		builder.setPositiveButton("\u786e\u5b9a", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				MyYouHuiActivity.this.dialogAddQuan.dismiss();
				if (MyYouHuiActivity.this.et_quan_ma.getText().toString() == null
						|| MyYouHuiActivity.this.et_quan_ma.getText().toString().replace(" ", "").trim().length() <= 0) {
					MainToast.show(MyYouHuiActivity.this, "\u8bf7\u8f93\u5165\u4f18\u60e0\u7801\uff01", 0);
				} else {
					MyYouHuiActivity.this.addQuanMa();
				}
			}
		});
		builder.setNegativeButton("\u53d6\u6d88", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				MyYouHuiActivity.this.dialogAddQuan.dismiss();
			}
		});
		return builder.create();
	}

	private void addQuanMa() {
		Map<String, String> map = new HashMap();
		map.put("code", this.et_quan_ma.getText().toString().replace(" ", "").trim());
		NetUtil.post(this, Constant.YOUHUIGETQUAN, map, new RequestCallBack<String>() {
			@Override
			public void onStart() {
				super.onStart();
				MyYouHuiActivity.this.dialogLoading.show();
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				MyYouHuiActivity.this.dialogAddQuan.dismiss();
				try {
					JSONObject jsonObject = new JSONObject(NetUtil.unescapeUnicode(responseInfo.result));
					if (jsonObject.getInt("code") == 10000) {
						MainToast.show(MyYouHuiActivity.this, "\u6dfb\u52a0\u6210\u529f\uff01", 0);
						MyYouHuiActivity.this.initData();
						return;
					}
					MyYouHuiActivity.this.dialogLoading.dismiss();
					MainToast.show(MyYouHuiActivity.this, jsonObject.getString("error"), 0);
				} catch (Exception e) {
					e.printStackTrace();
					MyYouHuiActivity.this.dialogLoading.dismiss();
					MainToast.show(MyYouHuiActivity.this, "\u670d\u52a1\u5668\u5fd9", 0);
				}
			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				MyYouHuiActivity.this.dialogLoading.dismiss();
				MyYouHuiActivity.this.dialogAddQuan.dismiss();
				MainToast.show(MyYouHuiActivity.this, MyYouHuiActivity.this.getResources().getString(R.string.netFail),
						0);
			}
		});
	}
}
